<?php
/**
 * Author: lf
 * Blog: https://blog.feehi.com
 * Email: job@feehi.com
 * Created at: 2017-12-27 14:53
 */

namespace common\helpers;

use feehi\cdn\QiniuTarget;
use yii\imagine\Image;
use Yii;
use yii\db\ActiveRecord;
use yii\helpers\FileHelper;
use yii\web\UploadedFile;

class Util
{

    /**
     * @param $base64
     * @param $path
     *
     * @return bool|string
     */
    public static function base64_upload($base64, $path)
    {
//        $base64_image = str_replace(' ', '+', $base64);
        $base64_image = $base64;
        //post的数据里面，加号会被替换为空格，需要重新替换回来，如果不是post的数据，则注释掉这一行
//        if (preg_match('/^(data:\s*image\/(\w+);base64,)/', $base64_image, $result)) {
        //匹配成功


        $image_name = uniqid() . '.' . 'png'; //文件名
        $image_file = $path . '/' . $image_name; //详细路径
        //服务器文件存储路径
        /** @var QiniuTarget $cdn */
        $cdn = Yii::$app->get("cdn");
        if (file_put_contents($image_file, base64_decode($base64_image))) {
           $name = 'uploads/' . $image_name;
            $cdn->upload($image_file,$name);
            return $name;
        } else {
            return false;
        }

    }


    /**
     * @param ActiveRecord $model
     * @param              $field
     * @param              $insert
     * @param              $uploadPath
     * @param array        $options
     *
     * @return bool
     * @throws \yii\base\Exception
     * @throws \yii\base\InvalidConfigException
     */
    public static function handleImgUpload(ActiveRecord &$model, $field, $insert, $uploadPath, $options = [])
    {
        $upload = UploadedFile::getInstanceByName($field); //UploadedFile类型

//        return var_dump($upload);
        if ($upload == null) {
            $upload = UploadedFile::getInstanceByName('file');
        }
        /* @var $cdn \feehi\cdn\TargetInterface */
        $cdn = yii::$app->get('cdn');
        if ($upload !== null) {
            $uploadPath = yii::getAlias($uploadPath);
            if (strpos(strrev($uploadPath), '/') !== 0) {
                $uploadPath .= '/';
            } //判断是不是目录
            if ( ! FileHelper::createDirectory($uploadPath)) { //创建目录
                $model->addError($field, "Create directory failed " . $uploadPath);

                return false;
            }
            //可以在options设置文件名
//			$realName =isset( $options['filename'] ) ?  $options['filename'] :  date( 'YmdHis' ) . '_' . uniqid() . '.' . $upload->getExtension();
            $fullName = isset($options['filename']) ? $uploadPath . $options['filename'] : $uploadPath . date('YmdHis') . '_' . uniqid() . '.' . $upload->getExtension();
            if ( ! $upload->saveAs($fullName)) {
                $model->addError($field, yii::t('app', 'Upload {attribute} error: ' . $upload->error,
                        ['attribute' => yii::t('app', ucfirst($field))]) . ': ' . $fullName);

                return false;
            }
            $model->$field = str_replace(yii::getAlias('@api/'), '', $fullName);


            $cdn->upload($fullName, $model->$field); //上传cnd，修改文件名
            if (isset($options['thumbSizes'])) {
                self::thumbnails($fullName, $options['thumbSizes']);
            }//缩略图操作
            if ( ! $insert) {
                $file = yii::getAlias('@frontend/web') . $model->getOldAttribute($field);
                if (file_exists($file) && is_file($file)) {
                    unlink($file);
                }//有这个 文件就删除
                if ($cdn->exists($model->getOldAttribute($field))) {
                    $cdn->delete($model->getOldAttribute($field));
                }//查看cdn上有没有这个文件
                if (isset($options['thumbSizes'])) {
                    self::deleteThumbnails($file, $options['thumbSizes']);
                }
            }
        } else {
            if ($model->$field === '0') {//删除
                $file = yii::getAlias('@frontend/web') . $model->getOldAttribute($field);
                if (file_exists($file) && is_file($file)) {
                    unlink($file);
                }
                if ($cdn->exists($model->getOldAttribute($field))) {
                    $cdn->delete($model->getOldAttribute($field));
                }
                if (isset($options['thumbSizes'])) {
                    self::deleteThumbnails($file, $options['thumbSizes']);
                }
                $model->$field = '';
            } else {
                if ($insert) {
                    $model->$field = '';
                } else {
                    $model->$field = $model->getOldAttribute($field);
                }
            }
        }
    }


    /**
     * 处理单模型单文件上传
     *
     * @param ActiveRecord $model
     * @param              $field
     * @param              $insert
     * @param              $uploadPath
     * @param array        $options
     *                  $options[thumbSizes] array 需要截图的尺寸，如[['w'=>100,'h'=>100]]
     *                  $options['filename'] string 新文件名，默认自动生成
     *
     * @return bool
     * @throws \yii\base\Exception
     */
    public static function handleModelSingleFileUpload(
        ActiveRecord &$model,
        $field,
        $insert,
        $uploadPath,
        $options = []
    ) {
        $upload = UploadedFile::getInstance($model, $field); //返回文件名
        /* @var $cdn \feehi\cdn\TargetInterface */
        $cdn = yii::$app->get('cdn');
        if ($upload !== null) {
            $uploadPath = yii::getAlias($uploadPath);
            if (strpos(strrev($uploadPath), '/') !== 0) {
                $uploadPath .= '/';
            } //判断是不是目录
            if ( ! FileHelper::createDirectory($uploadPath)) { //创建目录
                $model->addError($field, "Create directory failed " . $uploadPath);

                return false;
            }
            //可以在options设置文件名
            $fullName = isset($options['filename']) ? $uploadPath . $options['filename'] : $uploadPath . date('YmdHis') . '_' . uniqid() . '.' . $upload->getExtension();
            if ( ! $upload->saveAs($fullName)) {
                $model->addError($field, yii::t('app', 'Upload {attribute} error: ' . $upload->error,
                        ['attribute' => yii::t('app', ucfirst($field))]) . ': ' . $fullName);

                return false;
            }
            $model->$field = str_replace(yii::getAlias('@frontend/web'), '', $fullName);
            $cdn->upload($fullName, $model->$field); //上传cnd，修改文件名
            if (isset($options['thumbSizes'])) {
                self::thumbnails($fullName, $options['thumbSizes']);
            }//缩略图操作
            if ( ! $insert) {
                $file = yii::getAlias('@frontend/web') . $model->getOldAttribute($field);
                if (file_exists($file) && is_file($file)) {
                    unlink($file);
                }//有这个 文件就删除
                if ($cdn->exists($model->getOldAttribute($field))) {
                    $cdn->delete($model->getOldAttribute($field));
                }//查看cdn上有没有这个文件
                if (isset($options['thumbSizes'])) {
                    self::deleteThumbnails($file, $options['thumbSizes']);
                }
            }
        } else {
            if ($model->$field === '0') {//删除
                $file = yii::getAlias('@frontend/web') . $model->getOldAttribute($field);
                if (file_exists($file) && is_file($file)) {
                    unlink($file);
                }
                if ($cdn->exists($model->getOldAttribute($field))) {
                    $cdn->delete($model->getOldAttribute($field));
                }
                if (isset($options['thumbSizes'])) {
                    self::deleteThumbnails($file, $options['thumbSizes']);
                }
                $model->$field = '';
            } else {
                if ($insert) {
                    $model->$field = '';
                } else {
                    $model->$field = $model->getOldAttribute($field);
                }
            }
        }
    }

    /**
     * 处理单模型单文件非常态上传
     *
     * @param ActiveRecord $model
     * @param              $field
     * @param              $uploadPath
     * @param              $oldFullname
     * @param array        $options
     *
     * @return bool
     * @throws \yii\base\Exception
     */
    public static function handleModelSingleFileUploadAbnormal(
        ActiveRecord &$model,
        $field,
        $uploadPath,
        $oldFullname,
        $options = []
    ) {
        if ( ! isset($options['successDeleteOld'])) {
            $options['successDeleteOld'] = true;
        }//成功后删除旧文件
        if ( ! isset($options['deleteOldFile'])) {
            $options['deleteOldFile'] = false;
        }//删除旧文件
        $upload = UploadedFile::getInstance($model, $field);
        /* @var $cdn \feehi\cdn\TargetInterface */
        $cdn = yii::$app->get('cdn');
        if ($upload !== null) {
            $uploadPath = yii::getAlias($uploadPath);
            if (strpos(strrev($uploadPath), '/') !== 0) {
                $uploadPath .= '/';
            }
            if ( ! FileHelper::createDirectory($uploadPath)) {
                $model->addError($field, "Create directory failed " . $uploadPath);

                return false;
            }
            $fullName = isset($options['filename']) ? $uploadPath . $options['filename'] : $uploadPath . date('YmdHis') . '_' . uniqid() . '.' . $upload->getExtension();
            if ( ! $upload->saveAs($fullName)) {
                $model->addError($field, yii::t('app', 'Upload {attribute} error: ' . $upload->error,
                        ['attribute' => yii::t('app', ucfirst($field))]) . ': ' . $fullName);

                return false;
            }
            $model->$field = str_replace(yii::getAlias('@frontend/web'), '', $fullName);
            $cdn->upload($fullName, $model->$field);
            if (isset($options['thumbSizes'])) {
                self::thumbnails($fullName, $options['thumbSizes']);
            }
            if ($options['successDeleteOld'] && $oldFullname) {
                $file = yii::getAlias('@frontend/web') . $oldFullname;
                if (file_exists($file) && is_file($file)) {
                    unlink($file);
                }
                if ($cdn->exists($oldFullname)) {
                    $cdn->delete($oldFullname);
                }
                if (isset($options['thumbSizes'])) {
                    self::deleteThumbnails($file, $options['thumbSizes']);
                }
            }
        } else {
            if ($model->$field === '0') {//删除
                $file = yii::getAlias('@frontend/web') . $oldFullname;
                if (file_exists($file) && is_file($file)) {
                    unlink($file);
                }
                if ($cdn->exists($oldFullname)) {
                    $cdn->delete($oldFullname);
                }
                if (isset($options['thumbSizes'])) {
                    self::deleteThumbnails($file, $options['thumbSizes']);
                }
                $model->$field = '';
            } else {
                $model->$field = $oldFullname;
            }
        }
        if ($options['deleteOldFile']) {
            $file = yii::getAlias('@frontend/web') . $oldFullname;
            if (file_exists($file) && is_file($file)) {
                unlink($file);
            }
            if ($cdn->exists($oldFullname)) {
                $cdn->delete($oldFullname);
            }
            if (isset($options['thumbSizes'])) {
                self::deleteThumbnails($file, $options['thumbSizes']);
            }
        }
    }

    /**
     * 生成各个尺寸的缩略图
     *
     * @param       $fullName string 原图路径
     * @param array $thumbSizes 二维数组 如 [["w"=>110,"height"=>"20"],["w"=>200,"h"=>"30"]]则生成两张缩量图，分别为宽110高20和宽200高30
     */
    public static function thumbnails($fullName, array $thumbSizes)
    {
        foreach ($thumbSizes as $info) {
            $thumbFullName = self::getThumbName($fullName, $info['w'], $info['h']);
            Image::thumbnail($fullName, $info['w'], $info['h'])->save($thumbFullName);
            /** @var $cdn \feehi\cdn\TargetInterface */
            $cdn = yii::$app->get('cdn');
            $cdn->upload($thumbFullName, str_replace(yii::getAlias('@frontend/web'), '', $thumbFullName));
        }
    }

    /**
     * 删除各个尺寸的缩略图
     *
     * @param $fullName string 原图图片路径
     * @param $thumbSizes array 二维数组 如 [["w"=>110,"height"=>"20"],["w"=>200,"h"=>"30"]]则生成两张缩量图，分别为宽110高20和宽200高30
     */
    public static function deleteThumbnails($fullName, array $thumbSizes, $deleteOrigin = false)
    {
        foreach ($thumbSizes as $info) {
            $thumbFullName = self::getThumbName($fullName, $info['w'], $info['h']);
            if (file_exists($thumbFullName) && is_file($thumbFullName)) {
                unlink($thumbFullName);
            }
            $cdn = yii::$app->get('cdn');
            $cdn->delete(str_replace(yii::getAlias("@frontend/web"), '', $thumbFullName));
        }
        if ($deleteOrigin) {
            file_exists($fullName) && unlink($fullName);
        }
    }

    /**
     * 根据原图路径生成缩略图路径
     *
     * @param $fullName string 原图路径
     * @param $width int 长
     * @param $heith int 宽
     *
     * @return string 如/path/to/uploads/article/xx@100x20.png
     */
    public static function getThumbName($fullName, $width, $heith)
    {
        $dotPosition = strrpos($fullName, '.');
        $thumbExt    = "@" . $width . 'x' . $heith;
        if ($dotPosition === false) {
            $thumbFullName = $fullName . $thumbExt;
        } else {
            $thumbFullName = substr_replace($fullName, $thumbExt, $dotPosition, 0);
        }

        return $thumbFullName;
    }
}